package com.tony.demo.ui.widgets;

import android.annotation.SuppressLint;
import android.widget.TextView;

import com.blankj.utilcode.util.SpanUtils;
import com.puhui.lib.utils.TimeUtils;
import com.tony.demo.R;
import com.tony.demo.mvp.presenter.impl.BasePresenter;
import com.tony.demo.ui.base.BaseActivity;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SportTimeActivity extends BaseActivity {
    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_sport_time;
    }

    private Disposable subscribe;
    private int currentSportsTime = 0;

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        super.initView();

        TextView currentTimeTv = findViewById(R.id.currentTimeTv);
        TextView sportTimeTv = findViewById(R.id.sportTimeTv);

        currentTimeTv.setText(getTime());
//        sportTimeTv.setText(TimeUtils.formatDuring(currentSportsTime));
        setSportTimeData(sportTimeTv, 0, 0);

        subscribe = Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        currentTimeTv.setText(getTime());
                        currentSportsTime += 1000;

//                        sportTimeTv.setText(TimeUtils.formatDuring(currentSportsTime * 1000));
                        setSportTimeData(sportTimeTv,
                                TimeUtils.getMinutesOfTime(currentSportsTime), TimeUtils.getSecondsOfTime(currentSportsTime));
                    }
                });
    }

    private void setSportTimeData(TextView sportTimeTv, int minutes, int seconds) {
        SpanUtils.with(sportTimeTv)
                .append(minutes + "")
                .setFontSize(100, true)
                .append(" : ")
                .append(seconds + "")
                .setFontSize(100, true)
                .append(" S")
                .create();
    }

    private String getTime() {
        return TimeUtils.getTime(System.currentTimeMillis(), new SimpleDateFormat("HH:mm:ss", Locale.CHINA));
    }

    @Override
    protected void onDestroy() {
        if (null != subscribe) {
            subscribe.dispose();
        }
        super.onDestroy();
    }
}
